using MediatR;
using Medical.Domain;
using Medical.Infrastructrue.Interfaces;
using Medical.Infrastructrue.Utils;
using Medical.WriteApi.Appcontext.Command;
using Medical.WriteApi.Dto;

namespace Medical.WriteApi.Appcontext.CommandHandler
{
	public class UpdateUserCommandHandler : IRequestHandler<UpdateUserCommand, UserDto>
	{
		private readonly IBaseRepository<User> _userRepo;

		public UpdateUserCommandHandler(IBaseRepository<User> userRepo)
		{
			_userRepo = userRepo;
		}

		public async Task<UserDto> Handle(UpdateUserCommand request, CancellationToken cancellationToken)
		{
			var user = await _userRepo.GetModel(x => 
				x.UserId == request.UserId && !x.IsDeleted);
			
			if (user == null)
			{
				throw new Exception("用户不存在");
			}

			// 更新字段
			if (request.Email != null) user.Email = request.Email;
			if (request.FullName != null) user.FullName = request.FullName;
			if (request.Phone != null) user.Phone = request.Phone;
			if (request.EmployeeId.HasValue) user.EmployeeId = request.EmployeeId;
			if (request.IsActive.HasValue) user.IsActive = request.IsActive.Value;
			
			// 更新密码
			if (!string.IsNullOrWhiteSpace(request.NewPassword))
			{
				user.PasswordHash = PasswordHasher.HashPassword(request.NewPassword);
			}

			user.UpdatedAt = DateTime.Now;
			await _userRepo.UpdateAsync(user);

			return new UserDto
			{
				UserId = user.UserId,
				UserName = user.UserName,
				Email = user.Email,
				FullName = user.FullName,
				Phone = user.Phone,
				EmployeeId = user.EmployeeId,
				IsActive = user.IsActive,
				LastLoginAt = user.LastLoginAt,
				LastLoginIp = user.LastLoginIp,
				CreatedAt = user.CreatedAt,
				UpdatedAt = user.UpdatedAt
			};
		}
	}
}

